package com.scorpionstudio.girlstoryshop;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.DecelerateInterpolator;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.loopj.android.image.SmartImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.scorpionstudio.girlstoryshop.data.CacheItems;
import com.scorpionstudio.girlstoryshop.utils.JsonParser;
import com.scorpionstudio.girlstoryshop.utils.Variable;

public class DetailClothesActivity extends ScorpionActivity implements OnClickListener{
	private final String TAG = "DetailClothesActivity";
	private ImageView mBack;
	private TextView tvDescription,tvCost,tvMaSP,tvStatus;
	private SmartImageView smtAvata;
//	private ImageView smtItemDes;
	private MyTask mTask = null;
	private ProgressDialog pDialog;
	private String detail;
	private WebView myView;
	private int mShortAnimationDuration;
	private Animator mCurrentAnimator;
//	final View thumb1View = findViewById(R.id.imv_avata_des);
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_clothes_detail);
		ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));
		initVariable();
	}
	@SuppressLint("SetJavaScriptEnabled")
	public void initVariable(){
		mBack = (ImageView) findViewById(R.id.imv_detail_back);
		mBack.setOnClickListener(this);
		tvDescription = (TextView) findViewById(R.id.tv_des);
		tvMaSP = (TextView) findViewById(R.id.tv_msp);
		tvCost = (TextView) findViewById(R.id.tv_cost);
		tvStatus = (TextView) findViewById(R.id.tv_status);
		smtAvata = (SmartImageView) findViewById(R.id.imv_avata_des);
		
		myView = (WebView) findViewById(R.id.web_des);
		myView.getSettings().setJavaScriptEnabled(true);
		myView.getSettings().setDomStorageEnabled(true);
		myView.getSettings().setBuiltInZoomControls(true);
		myView.getSettings().setLoadWithOverviewMode(true);
		myView.getSettings().setSupportZoom(false);
		myView.getSettings().setUseWideViewPort(true);
		myView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
		myView.setInitialScale(120);

		if (CacheItems.getInstance().getmItem() != null) {
			tvDescription.setText(CacheItems.getInstance().getmItem().getDescriptionImg().trim());
			tvCost.setText(CacheItems.getInstance().getmItem().getCostItems().trim());
			smtAvata.setImageUrl(CacheItems.getInstance().getmItem().getUrlImg());
			detail = CacheItems.getInstance().getmItem().getDetail();
			mTask = new MyTask();
			mTask.execute(detail);
		}
		mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);
		smtAvata.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				zoomImageFromThumb(smtAvata, CacheItems.getInstance().getmItem().getUrlImg());
			}
		});
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imv_detail_back:
			finish();
			break;

		default:
			break;
		}
		
	}
	public void buyItem(View v){
		Intent mBuyItem = new Intent(DetailClothesActivity.this,BuyScreenActivity.class);
		// Name
		String nameClothes = tvDescription.getText().toString();
		mBuyItem.putExtra(Variable.KEY_NAME_CLOTHES, nameClothes);
		//Cost
		String costClothes = tvCost.getText().toString();
		mBuyItem.putExtra(Variable.KEY_COST_CLOTHES, costClothes);
		//MSP
		String maSP = tvMaSP.getText().toString();
		mBuyItem.putExtra(Variable.KEY_CLOTHES, maSP);
		startActivity(mBuyItem);
		finish();
	}
	@Override
	public void onBackPressed() {
		finish();
	}
	private class MyTask extends AsyncTask<String, Void, Void> {
		String maSp = "";
		String status = "";
		String linkIMG = "";
        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(DetailClothesActivity.this);
            pDialog.setMessage("Tải dữ liệu...");
            pDialog.setCancelable(true);
            pDialog.setCanceledOnTouchOutside(false);
            pDialog.setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
                    cancel(true);
                }
            });
            pDialog.show();
        }

        @Override
        protected Void doInBackground(String... params) {
        	  String json = JsonParser.getJSONString(params[0]);
        	  Log.i(TAG, json);
              JSONObject object;
			try {
				object = (JSONObject) new JSONTokener(json).nextValue();
				JSONArray mJsonArray  = object.getJSONArray(Variable.ROOT_DETAILS);
				JSONObject objJson = mJsonArray.getJSONObject(0);
				maSp = objJson.getString(Variable.MASP);
				linkIMG = objJson.getString(Variable.KEY_DETAIL_IMAGE);
				JSONObject objJson2 = mJsonArray.getJSONObject(1);
				status = objJson2.getString(Variable.STATUS);
			} catch (JSONException e) {
				e.printStackTrace();
			}
              
            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
        @Override
        protected void onPostExecute(Void result) {
        	tvMaSP.setText(maSp.trim());
        	tvStatus.setText(status.trim());
        	if(linkIMG.equals(null)){
        		myView.loadUrl("http://girlstory.vn/");
        	}else{
        		myView.loadUrl(linkIMG);
        	}
//        	ImageLoader.getInstance().displayImage(linkIMG,smtItemDes);
//        	ImageLoader.getInstance().displayImage(linkIMG, smtItemDes);
    		//smtItemDes.setImageUrl(linkIMG);
        	pDialog.dismiss();
        }
    }
	public void eventCall(View v){
		Intent callIntent = new Intent(Intent.ACTION_CALL);
	    callIntent.setData(Uri.parse("tel:0962004605"));
	    callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
	    startActivity(callIntent);
	}
	/*
	 * Zoom SmartImageView
	 * @ developer.android.com
	 */
	@SuppressLint("InlinedApi")
	private void zoomImageFromThumb(final View thumbView, String urlImg) {
	    if (mCurrentAnimator != null) {
	        mCurrentAnimator.cancel();
	    }

	    final SmartImageView expandedImageView = (SmartImageView) findViewById(
	            R.id.expanded_image);
	    expandedImageView.setImageUrl(urlImg);

	    final Rect startBounds = new Rect();
	    final Rect finalBounds = new Rect();
	    final Point globalOffset = new Point();

	    // The start bounds are the global visible rectangle of the thumbnail,
	    // and the final bounds are the global visible rectangle of the container
	    // view. Also set the container view's offset as the origin for the
	    // bounds, since that's the origin for the positioning animation
	    // properties (X, Y).
	    thumbView.getGlobalVisibleRect(startBounds);
	    findViewById(R.id.container)
	            .getGlobalVisibleRect(finalBounds, globalOffset);
	    startBounds.offset(-globalOffset.x, -globalOffset.y);
	    finalBounds.offset(-globalOffset.x, -globalOffset.y);

	    // Adjust the start bounds to be the same aspect ratio as the final
	    // bounds using the "center crop" technique. This prevents undesirable
	    // stretching during the animation. Also calculate the start scaling
	    // factor (the end scaling factor is always 1.0).
	    float startScale;
	    if ((float) finalBounds.width() / finalBounds.height()
	            > (float) startBounds.width() / startBounds.height()) {
	        // Extend start bounds horizontally
	        startScale = (float) startBounds.height() / finalBounds.height();
	        float startWidth = startScale * finalBounds.width();
	        float deltaWidth = (startWidth - startBounds.width()) / 2;
	        startBounds.left -= deltaWidth;
	        startBounds.right += deltaWidth;
	    } else {
	        // Extend start bounds vertically
	        startScale = (float) startBounds.width() / finalBounds.width();
	        float startHeight = startScale * finalBounds.height();
	        float deltaHeight = (startHeight - startBounds.height()) / 2;
	        startBounds.top -= deltaHeight;
	        startBounds.bottom += deltaHeight;
	    }

	    // Hide the thumbnail and show the zoomed-in view. When the animation
	    // begins, it will position the zoomed-in view in the place of the
	    // thumbnail.
	    thumbView.setAlpha(0f);
	    expandedImageView.setVisibility(View.VISIBLE);

	    // Set the pivot point for SCALE_X and SCALE_Y transformations
	    // to the top-left corner of the zoomed-in view (the default
	    // is the center of the view).
	    expandedImageView.setPivotX(0f);
	    expandedImageView.setPivotY(0f);

	    // Construct and run the parallel animation of the four translation and
	    // scale properties (X, Y, SCALE_X, and SCALE_Y).
	    AnimatorSet set = new AnimatorSet();
	    set
	            .play(ObjectAnimator.ofFloat(expandedImageView, View.X,
	                    startBounds.left, finalBounds.left))
	            .with(ObjectAnimator.ofFloat(expandedImageView, View.Y,
	                    startBounds.top, finalBounds.top))
	            .with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X,
	            startScale, 1f)).with(ObjectAnimator.ofFloat(expandedImageView,
	                    View.SCALE_Y, startScale, 1f));
	    set.setDuration(mShortAnimationDuration);
	    set.setInterpolator(new DecelerateInterpolator());
	    set.addListener(new AnimatorListenerAdapter() {
	        @Override
	        public void onAnimationEnd(Animator animation) {
	            mCurrentAnimator = null;
	        }

	        @Override
	        public void onAnimationCancel(Animator animation) {
	            mCurrentAnimator = null;
	        }
	    });
	    set.start();
	    mCurrentAnimator = set;

	    // Upon clicking the zoomed-in image, it should zoom back down
	    // to the original bounds and show the thumbnail instead of
	    // the expanded image.
	    final float startScaleFinal = startScale;
	    expandedImageView.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View view) {
	            if (mCurrentAnimator != null) {
	                mCurrentAnimator.cancel();
	            }

	            // Animate the four positioning/sizing properties in parallel,
	            // back to their original values.
	            AnimatorSet set = new AnimatorSet();
	            set.play(ObjectAnimator
	                        .ofFloat(expandedImageView, View.X, startBounds.left))
	                        .with(ObjectAnimator
	                                .ofFloat(expandedImageView, 
	                                        View.Y,startBounds.top))
	                        .with(ObjectAnimator
	                                .ofFloat(expandedImageView, 
	                                        View.SCALE_X, startScaleFinal))
	                        .with(ObjectAnimator
	                                .ofFloat(expandedImageView, 
	                                        View.SCALE_Y, startScaleFinal));
	            set.setDuration(mShortAnimationDuration);
	            set.setInterpolator(new DecelerateInterpolator());
	            set.addListener(new AnimatorListenerAdapter() {
	                @Override
	                public void onAnimationEnd(Animator animation) {
	                    thumbView.setAlpha(1f);
	                    expandedImageView.setVisibility(View.GONE);
	                    mCurrentAnimator = null;
	                }

	                @Override
	                public void onAnimationCancel(Animator animation) {
	                    thumbView.setAlpha(1f);
	                    expandedImageView.setVisibility(View.GONE);
	                    mCurrentAnimator = null;
	                }
	            });
	            set.start();
	            mCurrentAnimator = set;
	        }
	    });
	}
}
